package net.zdreamer.shunyi.adapter;

import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

public abstract class MyBaseAdapter<T> extends BaseAdapter {

    // 这个类不支持移除操作

    public static final int VIEWTYPE_ID_DATA = 0;

    public static final int VIEWTYPE_ID_LOAD = 1;

    public static final int VIEWTYPE_ID_MORE = 2;

    public static final int VIEWTYPE_ID_COUNT = 3;

    /** 是否还有剩余 */
    private boolean mHasLeft = true;

    /** 页面大小 */
    private final int mPageSize;

    /** 结果集 */
    private List<T> mResult = null;

    /** 系统上下文 */
    private Context mContext = null;

    public Context getmContext() {
		return mContext;
	}

	/** 布局映射器 */
    private final LayoutInflater mInflater;

    /** 列表项布局ID */
    private final int mRes;

    /** “载入中”布局ID */
    private final int mLoadingRes;

    private final int mRetryRes;

    /** 载入更多的回调方法 */
    // private final INduoaPageAdapter<T> mCallback;

    /** 加载更多的起始索引 */
    private int mStart = 0;

    /** 临时的加载数据 */
    // private List<T> tmps;

    /** 判断是否正在加载数据，防止重复加载 */
    private boolean isLoadingData = false;

    public static final int DEFAULT_PAGE_SIZE = 20;

    /**
     * 标识, 加载本页数据失败
     */
    private boolean mIsFailLoad;

    public MyBaseAdapter(Context context, List<T> list, int pageSize, int res, int loadingRes,
            int retryRes) {
        mContext = context;
        mInflater = LayoutInflater.from(mContext);
        mResult = list;
        mPageSize = pageSize;
        mRes = res;
        mLoadingRes = loadingRes;
        mRetryRes = retryRes;

        if (list.size() < pageSize) {
            mHasLeft = false;
        } else {
            mHasLeft = true;
        }

    }

    public MyBaseAdapter(Context context, List<T> list, int res) {
        mContext = context;
        mInflater = LayoutInflater.from(mContext);
        mResult = list;
        mPageSize = Integer.MAX_VALUE;
        mRes = res;
        mLoadingRes = 0;
        mRetryRes = 0;
        mHasLeft = false;
    }

    public List<T> getResult() {
        return mResult;
    }

    public void setInitData(List<T> iniData) {
        mResult = iniData;
        mStart += iniData.size();
        if (mResult.size() < mPageSize) {
            mHasLeft = false;
        } else {
            mHasLeft = true;
        }
    }

    public void addResult(List<T> iniData) {
        mResult.addAll(iniData);
    }

    public void reSetResult(List<T> iniData) {
        mResult = iniData;
    }

    public void reSetDataStart() {
        mStart = 0;
    }

    @Override
    public int getCount() {
        if (mResult == null) {
            return 0;
        }
        return mHasLeft ? mResult.size() + 1 : mResult.size();
    }

    /**
     * 返回数据item的个数
     * 
     * @return count
     */
    protected int getDataCount() {
        return null == mResult ? 0 : mResult.size();
    }

    @Override
    public int getViewTypeCount() {
        return VIEWTYPE_ID_COUNT;
    }

    @Override
    public int getItemViewType(int position) {
        if (position >= getDataCount()) {
            if (mIsFailLoad) {
                return VIEWTYPE_ID_MORE;
            } else {
                return VIEWTYPE_ID_LOAD;
            }

        } else {
            return VIEWTYPE_ID_DATA;
        }
    }

    @Override
    public Object getItem(int position) {
        return position < mResult.size() ? mResult.get(position) : null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 初始化convertView
        if (null == convertView) {
            if (position == getDataCount()) {
                if (mIsFailLoad) {
                    convertView = mInflater.inflate(mRetryRes, parent, false);
                } else {
                    convertView = mInflater.inflate(mLoadingRes, parent, false);
                }
            } else {
                if (convertView == null && mRes != 0) {
                    convertView = mInflater.inflate(mRes, parent, false);
                }
            }
        }

        // 显示更多视图时, 添加监听事件
        if (position == getDataCount() && mIsFailLoad) {
            convertView.setOnClickListener(mMoreClickListener);
        }

        if (position == getDataCount()) {
            if (!mIsFailLoad && !isLoadingData) {
                isLoadingData = true;
                loadNextPage();
            }
        } else {
            convertView = getView(position, convertView, parent, mResult.get(position));
        }
        return convertView;
    }

    @Override
    public boolean isEnabled(int position) {

        // 加载视图或者更多视图, 都不可点击
        if (position == getDataCount()) {
            return false;
        }
        return super.isEnabled(position);
    }

    /**
     * 是否还有下一页的数据
     * 
     * @return true 有下一页
     */
    protected boolean hasNextPage() {
        return mHasLeft;
    }

    Handler mHandler = new Handler();

    // public interface INduoaPageAdapter<T> {
    /**
     * 加载指定start和size区域的数据
     * 
     * @param start 起始点
     * @param size 数量
     * @return null 加载失败; list.size < size 没有下一页数据; list.size == size 有下一页数据.
     */
    public void nextPage(int start, int size, ILoadNextPageData<T> iLoadNextPageData) {}

    public interface ILoadNextPageData<T> {
        public void loadNextPageData(List<T> t);
    }

    protected abstract View getView(int position, View convertView, ViewGroup parent, T value);

    // }

    private void loadNextPage() {
        nextPage(mStart, mPageSize, new ILoadNextPageData<T>() {

            @Override
            public void loadNextPageData(List<T> t) {
                handleNextPage(t);
            }
        });
    }

    /*
     * 处理下一页数据
     */
    private void handleNextPage(List<T> tmps) {
        if (null == tmps) {
            mHasLeft = true;
            mIsFailLoad = true;
            // Toast.makeText(mContext, "网络错误", Toast.LENGTH_LONG).show();
        } else if (mPageSize > tmps.size()) {
            mIsFailLoad = false;
            mResult.addAll(tmps);
            mStart += tmps.size();
            mHasLeft = false;
        } else {
            mHasLeft = true;
            mResult.addAll(tmps);
            mStart += tmps.size();
        }
        isLoadingData = false;
        notifyDataSetChanged();
    }

    private final View.OnClickListener mMoreClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (!isLoadingData) {
                isLoadingData = true;
                mIsFailLoad = false;
                loadNextPage();
                notifyDataSetChanged();
            }
        }
    };
}
